<template>
  <div class="global-box">
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <a-form-model
        class="agree"
        ref="ruleForm"
        :model="agreeForm"
        :rules="agreeFormRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="协议名称" prop="name" :wrapper-col="{ span: 6 }">
          <a-input v-model="agreeForm.name" placeholder="请输入协议名称" />
        </a-form-model-item>
        <a-form-model-item label="关联协议模板" v-if="temList === ''">
          <a @click="visible = true">选择协议模板</a>
          <a-table
            v-if="dataTem.length > 0"
            :columns="columnsTem"
            :data-source="dataTem"
            :pagination="false"
            :rowKey="record => record.id"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handleDelete(record)">删除</a>
              </template>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="协议内容" prop="type">
          <div class="content">
            <h3>《北京中业兴为科技集团有限公司课程购买协议》</h3>
            <div class="agreeInfo">
              <p class="indent">购买商品名称：</p>
              <p class="indent">购买商品类型：</p>
              <p class="indent">您所支付定金金额：</p>
              <p class="indent">您所支付全款金额：</p>
              <p class="indent">共计支付总金额：</p>
              <p class="indent">商品有效期：</p>
              <a-row class="info" :gutter="40">
                <a-col class="partyA" :span="10">
                  <p class="indent top">甲方：北京中业兴为科技集团有限公司</p>
                  <p class="indent bottom">日期：年月日</p>
                </a-col>
                <a-col class="partyB" :span="14">
                  <p><span>乙方：</span><a-input placeholder="请输入"></a-input></p>
                  <p><span>身份证号码：</span><a-input placeholder="请输入"></a-input></p>
                  <p class="tip margin">此处填写的信息仅用于暴涨用户购买服务的合法权益</p>
                  <p class="margin">日期：年月日</p>
                </a-col>
              </a-row>
            </div>
            <div class="agreeContent">
              <div class="cententTit">协议条款内容：</div>
              <div class="modelContent">
                <div v-for="(item, index) in clause" :key="index">
                  <p class="termTitle" v-if="item.content && item.content.length !== 0">
                    {{ item.title }}
                  </p>
                  <p
                    class="termTitle"
                    v-if="
                      index === 0 &&
                      (item.sub[0].content.length !== 0 ||
                        item.sub[1].content.length !== 0 ||
                        item.sub[2].content.length !== 0)
                    "
                  >
                    {{ item.title }}
                  </p>
                  <div v-if="item.sub">
                    <div v-for="(el, i) in item.sub" :key="i">
                      <p class="subtitle" v-if="el.content.length !== 0">{{ el.title }}</p>
                      <p class="text" v-for="(child, k) in el.content" :key="k">
                        {{ child }}
                      </p>
                    </div>
                  </div>
                  <div v-if="index !== 0">
                    <div v-for="(itemA, k) in item.content" :key="k">
                      <p class="text" v-if="item.content.length !== 0">
                        {{ itemA }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item style="text-align: center">
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-modal
        title="添加协议模板"
        :visible="visible"
        @ok="handleOk"
        @cancel="handleCancel"
        okText="提交"
        cancelText="取消"
        width="50%"
      >
        <div class="form-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="课程目录">
                  <a-cascader
                    :field-names="{ label: 'value', value: 'id', children: 'children' }"
                    :options="directoryOptions"
                    :load-data="loadData"
                    placeholder="请选择课程目录"
                    change-on-select
                    v-model="queryParam.directory"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="协议模板类型">
                  <a-select v-model="queryParam.type" placeholder="请选择协议模板类型">
                    <a-select-option :value="item.value" :key="item.value" v-for="item in typeList">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="所属事业部">
                  <a-select v-model="queryParam.shiYeBu" placeholder="请选择所属事业部">
                    <a-select-option
                      :value="item.jiGouTableId"
                      :key="item.jiGouTableId"
                      v-for="item in affiliationList"
                    >
                      {{ item.jiGouName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="协议模板ID">
                  <a-input v-model="queryParam.id" placeholder="请输入协议模板ID" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="协议模板标题">
                  <a-input v-model="queryParam.name" placeholder="请输入协议模板标题" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <span class="table-page-search-submitButtons" style="float: right">
                  <a-button type="primary" @click="search">筛选</a-button>
                  <a-button style="margin-left: 8px" @click="queryParam = {}">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          :rowSelection="rowSelection"
          :rowKey="record => record.id"
        >
        </a-table>
      </a-modal>
    </a-card>
  </div>
</template>
<script>
import { directory, list, affiliation, manageAdd } from '@/api/agreement/template'
export default {
  data () {
    return {
      columnsTem: [
        {
          title: '协议模板ID',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '协议模板名称',
          dataIndex: 'templateName',
          align: 'center'
        },
        {
          title: '课程目录',
          dataIndex: 'directoryName',
          align: 'center'
        },
        {
          title: '协议类型',
          dataIndex: 'templateCategory',
          align: 'center'
        },
        {
          title: '所属事业部',
          dataIndex: 'deptName',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      dataTem: [],
      columns: [{
        title: '协议模板ID',
        dataIndex: 'id',
        align: 'center'
      },
      {
        title: '协议模板名称',
        dataIndex: 'directoryName',
        align: 'center'
      },
      {
        title: '协议模板类型',
        dataIndex: 'templateCategory',
        align: 'center'
      },
      {
        title: '所属事业部',
        dataIndex: 'deptName',
        align: 'center'
      }],
      data: [],
      agreeForm: {
        name: ''
      },
      queryParam: {
        directory: [],
        type: undefined,
        shiYeBu: undefined,
        id: '',
        name: ''
      },
      pagination: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = 1
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
          this.getData()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.current = current
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getData()
        }
      },
      visible: false,
      labelCol: { span: 2 },
      wrapperCol: { span: 15 },
      agreeFormRules: {
        name: [{ required: true, message: '请输入协议名称', trigger: 'blur' }]
      },
      directoryOptions: [],
      selectedRowKeys: [],
      selectedRows: [],
      statusList: [
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 0
        }
      ],
      typeList: [{
        label: '通用',
        value: 1
      }, {
        label: '退费',
        value: 2
      }, {
        label: '重修',
        value: 3
      }, {
        label: '退费和重修',
        value: 4
      }],
      affiliationList: [],
      clause: [],
      temList: ''
    }
  },
  computed: {
    rowSelection () {
      const that = this
      return {
        type: 'radio',
        selectedRowKeys: that.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          that.selectedRowKeys = selectedRowKeys
          that.selectedRows = selectedRows
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: that.selectedRowKeys.indexOf(record.id) > -1
          }
        })
      }
    }
  },
  mounted () {
    this.getAffiliation()
    this.getDirectory()
    this.getData()
    if (this.$route.params.re !== '') {
      this.temList = this.$route.params.re
      this.dataTem.push(this.$route.params.re)
    }
  },
  methods: {
    // 获取列表数据
    getData () {
      const data = {
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize,
        deptId: this.queryParam.shiYeBu || 0,
        deptName: '',
        templateCategory: this.queryParam.type || 0,
        templateId: this.queryParam.id || 0,
        templateName: this.queryParam.name,
        directoryId: this.queryParam.directory[0] || 0,
        examId: this.queryParam.directory[1] || 0,
        enable: this.queryParam.status || 1
      }
      list(data).then(res => {
        if (res.code === '1') {
          this.pagination.total = res.data.totalSize
          this.data = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 提交
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.save()
        } else {
          return false
        }
      })
    },
    save () {
      if (this.dataTem.length === 0) {
        this.$message.error('请选择协议模板')
        return false
      }
      const data = {
        creatorId: this.dataTem[0].creatorId,
        creatorName: this.dataTem[0].creatorName,
        deptId: this.dataTem[0].deptId,
        directoryId: this.dataTem[0].directoryId,
        directoryName: this.dataTem[0].directoryName,
        enable: this.dataTem[0].enable,
        examId: this.dataTem[0].examId,
        examName: this.dataTem[0].examName,
        protocolCategory: this.dataTem[0].templateCategory,
        protocolName: '',
        protocolTemplateId: this.dataTem[0].id,
        protocolTemplateName: this.dataTem[0].templateName,
        refundAmount: 0,
        signNum: 0,
        studyNum: 0,
        studyYearNum: 0,
        validityTime: 0
      }
      manageAdd(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.$router.push({
            name: 'management'
          })
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 表格删除
    handleDelete (record) {
      this.dataTem = []
    },
    // 筛选
    search () {
      this.getData()
    },
    // 弹出框提交
    handleOk () {
      if (this.selectedRows.length === 0) {
        return false
      }
      this.dataTem = this.selectedRows
      this.visible = false
      this.clause = this.dataTem[0].otherClause !== '' && JSON.parse(this.dataTem[0].otherClause)
      this.pagination.current = 1
      this.pagination.defaultCurrent = 1
      this.selectedRowKeys = []
      this.selectedRows = []
      this.getData()
    },
    // 表格取消
    handleCancel () {
      this.pagination.current = 1
      this.pagination.defaultCurrent = 1
      this.selectedRowKeys = []
      this.selectedRows = []
      this.visible = false
      this.queryParam = {
        directory: [],
        type: undefined,
        shiYeBu: undefined,
        id: '',
        name: ''
      }
      this.getData()
    },
    // 表格全选
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 获取所属机构
    getAffiliation () {
      affiliation({}).then(res => {
        if (res.code === '1') {
          this.affiliationList = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      if (this.queryParam.directory[1]) {
        return false
      }
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.agree {
  .content {
    background: rgba(249, 249, 249, 1);
    padding: 30px;
  }
  p {
    line-height: 24px;
  }
  color: #000;
  .info {
    margin-top: 30px;
    margin-left: 0 !important;
    .partyA {
      position: relative;
      height: 168px;
      .top {
        position: absolute;
        top: 0;
        left: 0;
      }
      .bottom {
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }
    .partyB {
      p {
        display: flex;
        span {
          width: 30%;
          text-align: right;
          line-height: 32px;
          margin-right: 1%;
        }
      }
      .tip {
        color: firebrick;
      }
      .margin {
        margin-left: 6%;
      }
    }
  }
  h3 {
    text-align: center;
    font-size: 20px;
    margin-bottom: 30px;
  }
  .indent {
    text-indent: 2em;
  }
  .agreeContent {
    margin-top: 60px;
    .cententTit {
      margin-bottom: 30px;
    }
  }
}
</style>
